{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 🤗 Welcome to AdalFlow!\n",
    "## The library to build & auto-optimize any LLM task pipelines\n",
    "\n",
    "Thanks for trying us out, we're here to provide you with the best LLM application development experience you can dream of 😊 any questions or concerns you may have, [come talk to us on discord,](https://discord.gg/ezzszrRZvT) we're always here to help! ⭐ <i>Star us on <a href=\"https://github.com/SylphAI-Inc/AdalFlow\">Github</a> </i> ⭐\n",
    "\n",
    "\n",
    "# Quick Links\n",
    "\n",
    "Github repo: https://github.com/SylphAI-Inc/AdalFlow\n",
    "\n",
    "Full Tutorials: https://adalflow.sylph.ai/index.html#.\n",
    "\n",
    "Deep dive on each API: check out the [developer notes](https://adalflow.sylph.ai/tutorials/index.html).\n",
    "\n",
    "Common use cases along with the auto-optimization:  check out [Use cases](https://adalflow.sylph.ai/use_cases/index.html).\n",
    "\n",
    "# Author\n",
    "\n",
    "This notebook was created by [Li Yin](https://www.linkedin.com/in/li-yin-ai/).\n",
    "\n",
    "# Outline\n",
    "\n",
    "We will cover the process of using deepseek-r1 from hosted by together.\n",
    "To setup. Go to [together.ai](https://together.ai/) to get the API key\n",
    "\n",
    "\n",
    "**Next: Try our [auto-optimization](https://colab.research.google.com/drive/1n3mHUWekTEYHiBdYBTw43TKlPN41A9za?usp=sharing)**\n",
    "\n",
    "\n",
    "# Installation\n",
    "\n",
    "1. Use `pip` to install the `adalflow` Python package. We will need `together`extra packages.\n",
    "\n",
    "  ```bash\n",
    "  pip install adalflow[together]\n",
    "  ```\n",
    "2. Setup  `together` API key\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "zsh:1: no matches found: adalflow[together]\n"
     ]
    }
   ],
   "source": [
    "from IPython.display import clear_output\n",
    "\n",
    "!pip install -U adalflow[together]\n",
    "\n",
    "clear_output()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "API keys have been set.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "from getpass import getpass\n",
    "\n",
    "# Prompt user to enter their API keys securely\n",
    "together_api_key = getpass(\"Please enter your Together API key: \")\n",
    "\n",
    "\n",
    "# Set environment variables\n",
    "os.environ[\"TOGETHER_API_KEY\"] = together_api_key\n",
    "\n",
    "print(\"API keys have been set.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 😇 Have fun\n",
    "\n",
    "Let's get started!  🚀\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "GeneratorOutput(id=None, data={'think': \"Okay, the user wants a brief summary of generative AI. Let's start by defining what generative AI is. It's a type of artificial intelligence that can create new content, like text, images, or music. I should mention that it uses machine learning models, maybe specifically neural networks. Examples like GPT for text and DALL-E for images would be good to include. Also, note how it's applied in different fields such as content creation, design, and problem-solving. Need to keep it concise, so avoid technical jargon. Make sure to highlight its ability to learn from data and generate original outputs. Check if there's any common applications or impacts worth mentioning briefly.\", 'answer': 'Generative AI is a type of artificial intelligence that creates new content (text, images, code, etc.) by learning patterns from existing data. Using models like neural networks, it can generate original outputs, such as realistic images, coherent text, or music. Examples include tools like ChatGPT for text and DALL-E for images. It’s widely used in creative fields, automation, and problem-solving, though ethical concerns around accuracy and misuse remain.'}, error=None, usage=CompletionUsage(completion_tokens=231, prompt_tokens=56, total_tokens=287), raw_response=\"<think>\\nOkay, the user wants a brief summary of generative AI. Let's start by defining what generative AI is. It's a type of artificial intelligence that can create new content, like text, images, or music. I should mention that it uses machine learning models, maybe specifically neural networks. Examples like GPT for text and DALL-E for images would be good to include. Also, note how it's applied in different fields such as content creation, design, and problem-solving. Need to keep it concise, so avoid technical jargon. Make sure to highlight its ability to learn from data and generate original outputs. Check if there's any common applications or impacts worth mentioning briefly.\\n</think>\\n\\nGenerative AI is a type of artificial intelligence that creates new content (text, images, code, etc.) by learning patterns from existing data. Using models like neural networks, it can generate original outputs, such as realistic images, coherent text, or music. Examples include tools like ChatGPT for text and DALL-E for images. It’s widely used in creative fields, automation, and problem-solving, though ethical concerns around accuracy and misuse remain.\", metadata=None)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import adalflow as adal\n",
    "\n",
    "from adalflow.components.model_client import TogetherClient\n",
    "import re\n",
    "\n",
    "# parse the text as it starts with <think> and ends with </think>, then followed with the final answer\n",
    "\n",
    "\n",
    "@adal.func_to_data_component\n",
    "def extract_think_and_answer(text: str) -> str:\n",
    "    \"\"\"\n",
    "    Extracts text enclosed between <think>...</think> as 'think'\n",
    "    and the text after </think> as 'answer'.\n",
    "\n",
    "    Returns:\n",
    "        dict: {\n",
    "            \"think\": <content within <think>...</think>>,\n",
    "            \"answer\": <content after </think>>\n",
    "        }\n",
    "        or None if no match is found.\n",
    "    \"\"\"\n",
    "\n",
    "    # Use DOTALL so '.' will match newlines as well\n",
    "    pattern = r\"<think>(.*?)</think>([\\s\\S]*)\"\n",
    "    match = re.search(pattern, text, re.DOTALL)\n",
    "\n",
    "    if match:\n",
    "        return {\"think\": match.group(1).strip(), \"answer\": match.group(2).strip()}\n",
    "    return None\n",
    "\n",
    "\n",
    "# set up the generator\n",
    "\n",
    "generator = adal.Generator(\n",
    "    model_client=TogetherClient(),\n",
    "    model_kwargs={\n",
    "        \"model\": \"deepseek-ai/DeepSeek-R1\",\n",
    "        \"temperature\": 0.7,\n",
    "        \"max_tokens\": 2000,\n",
    "    },\n",
    "    output_processors=extract_think_and_answer,\n",
    ")\n",
    "\n",
    "# run the code\n",
    "prompt_kwargs = {\"input_str\": \"Hi from AdalFlow! Summarize generative AI briefly.\"}\n",
    "output = generator(prompt_kwargs=prompt_kwargs)\n",
    "output"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Issues and feedback\n",
    "\n",
    "If you encounter any issues, please report them here: [GitHub Issues](https://github.com/SylphAI-Inc/LightRAG/issues).\n",
    "\n",
    "For feedback, you can use either the [GitHub discussions](https://github.com/SylphAI-Inc/LightRAG/discussions) or [Discord](https://discord.gg/ezzszrRZvT)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "my-project-kernel",
   "language": "python",
   "name": "my-project-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
